package com.tenton.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @ClassName：TextUtil
 * @Description：txt读写工具类
 * @Author：tangdong
 * @Date：2022/11/4 10:12
 **/
@Slf4j
public class TextUtil {
    /**
     * 按行读取文本文件
     *
     * @param filePath       文件路径
     * @param lineReadAction
     * @return
     */
    public static void read(String filePath, Consumer<String> lineReadAction) {
        File file = new File(filePath);
        InputStreamReader inputStreamReader = null;
        BufferedReader br = null;
        try {
            if (file.exists()) {
                inputStreamReader = new InputStreamReader(new FileInputStream(file));
                br = new BufferedReader(inputStreamReader);
                String line;
                while ((line = br.readLine()) != null) {
                    lineReadAction.accept(line);
                }
            }
        } catch (FileNotFoundException e) {
            log.error("未找到文件：".concat(filePath));
            e.printStackTrace();
        } catch (IOException e) {
            log.error("读取行数据失败！");
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (inputStreamReader != null){
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                log.error("文本读取工具类 Reader 关闭失败！");
                e.printStackTrace();
            }


        }
    }

    /**
     * 读取圈闭文本
     *
     * @param filePath
     * @return
     */
    public static String readAll(String filePath) {
        File file = new File(filePath);
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException e) {
            log.error("未找到文件：".concat(filePath));
            e.printStackTrace();
        } catch (IOException e) {
            log.error("读取行数据失败！");
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error("文本读取工具类 BufferedReader 关闭失败！");
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String path = "xxx";
        List<String> list = new ArrayList<>();
        TextUtil.read(path, (String lineReadAction) -> {
            list.add(lineReadAction);
        });

    }
}
